package com.cuitrip.business.tripservice;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.TripBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.app.MainApplication;
import com.cuitrip.app.base.UnitUtils;
import com.cuitrip.business.bill.ExplainActivity;
import com.cuitrip.business.bill.Rate;
import com.cuitrip.business.notice.model.FeeDescription;
import com.cuitrip.business.pay.model.PayMode;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.presenter.TripEditPresenter;
import com.cuitrip.business.tripservice.proxy.PriceProxy;
import com.cuitrip.business.tripservice.ui.EditDetailLayout;
import com.cuitrip.business.webview.H5UrlMaker;
import com.cuitrip.business.webview.proxy.WebViewProxy;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.component.choicedialog.MultiItem;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.component.para.model.Para;
import com.cuitrip.component.para.proxy.ParaProxy;
import com.cuitrip.service.R;
import com.cuitrip.util.span.NoLineClickSpan;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ArrayUtil;
import com.lab.utils.NumberUtils;
import com.lab.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 费用说明页面
 * Created ak
 */
public class TripPayInstructionFragment extends CustomUiFragment implements IProxyCallback {

    public static final int PAY_INCLUDE_TYPE = 0x01;

    public static final int PAY_EXCLUDE_TYPE = 0x02;

    public static final int PAY_TYPE = 0x03;

    public static final int PRICE_TYPE = 0x04;

    public static final int PAY_CURRENCY_TYPE = 0x05;


    @Bind(R.id.pay_way_content)
    protected TextView mPayWayContent;


    @Bind(R.id.pay_count_content)
    protected EditText mPayCountContent;

    @Bind(R.id.pay_count_layout)
    protected View payCountLayout;

    @Bind(R.id.pay_include_layout)
    protected EditDetailLayout mPayIncludeLayout;

    @Bind(R.id.pay_exclude_layout)
    protected EditDetailLayout mPayExcludeLayout;

    @Bind(R.id.money_type)
    protected TextView mMoneyTypeView;

    @Bind(R.id.money_count_end)
    protected TextView mMoneyEndView;

    @Bind(R.id.full_content)
    protected View mFullContent;
    @Bind(R.id.currency_layout)
    protected ItemLayout currencyLayout;
    @Bind(R.id.tv_help_link)
    TextView tvHelpLink;
    private View mContentView;
    private ServiceInfo mServiceInfo;


    private ArrayList<CharSequence> includePayList = new ArrayList<>();
    private ArrayList<CharSequence> excludePayList = new ArrayList<>();

    private String priceType = "";

    private String price = "";

    private int mPayCount = 0;

    private ApiProxy mApiProxy = new ApiProxy(this);

    private TripEditPresenter mTripMainUpdater;
    private ArrayList<FeeDescription> notice;
    private boolean isFirstClick=true;

    public void setTripMainUpdater(TripEditPresenter tripMainUpdater) {
        this.mTripMainUpdater = tripMainUpdater;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = super.onCreateView(inflater, container, savedInstanceState, R.layout.page_pay_instruction);
        return mContentView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mServiceInfo = (ServiceInfo) bundle.getSerializable(ServiceInfo.KEY);
        }
        super.onCreate(savedInstanceState);
    }


    @Override
    public void initView() {
        ButterKnife.bind(this, mContentView);
        mPayCountContent.setTypeface(MainApplication.getInstance().getIconFont());
        String moneyEnd = getString(R.string.trip_attribute_price_value_per_person);
        int index = moneyEnd.lastIndexOf("/");
        if (index >= 0) {
            moneyEnd = moneyEnd.substring(index, moneyEnd.length());
        }
        mMoneyEndView.setText(moneyEnd);
        initNavigation();
        initTitle();
        //// TODO: 16/3/14,h5url替换

        String helpLink = getString(R.string.trip_price_desc_1,R.string.trip_price_desc_2);
        String link = getString(R.string.trip_price_desc_2);
        SpannableString ss = new SpannableString(link);
        ss.setSpan(new NoLineClickSpan() {
            @Override
            public void onClick(View widget) {
                WebViewProxy.getInstance().browseWeb(getHostActivity(), H5UrlMaker.getInsiderAgreement());
            }
        }, 0, link.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.sky_blue_00d4ff)), 0, link.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvHelpLink.setText(ss);
        tvHelpLink.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    public void initData() {
        TripBusiness.getInfoPages(mApiProxy, "1");
        initValues();
        bindValueToLayout(PAY_TYPE, PRICE_TYPE, PAY_CURRENCY_TYPE, PAY_INCLUDE_TYPE, PAY_EXCLUDE_TYPE);
        updatePriceType();
    }

    public void initListener() {
        mPayCountContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_DONE) {
                    String payCount = textView.getText().toString();
                    mPayCount = (int) NumberUtils.parseFloat(payCount);
                    String formatPayCount = NumberUtils.getMoneyFormat(payCount);
                    textView.setText(formatPayCount);
                    mPayCountContent.setSelection(mPayCountContent.length());
                }
                return false;
            }
        });

        mPayCountContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (isFirstClick && hasFocus){
                    startOtherPage();
                    isFirstClick=false;
                }
            }
        });

    }

    private void initValues() {

        if (mServiceInfo != null) {
            if (!TextUtils.isEmpty(mServiceInfo.getPriceType())) {
                priceType = mServiceInfo.getPriceType();
            } else {
                priceType = ServiceInfo.PAYWAY_FREE;
            }
            if (!TextUtils.isEmpty(mServiceInfo.getPrice())) {
                price = mServiceInfo.getPrice();
            }
            if (!TextUtils.isEmpty(mServiceInfo.getFeeExclude())) {
                excludePayList.clear();
                excludePayList.addAll(ParaProxy.getInstance().getParaList(mServiceInfo.getFeeExclude()));
            }
            if (!TextUtils.isEmpty(mServiceInfo.getFeeInclude())) {
                includePayList.clear();
                includePayList.addAll(ParaProxy.getInstance().getParaList(mServiceInfo.getFeeInclude()));
            }
            if (TextUtils.isEmpty(mServiceInfo.getMoneyType())) {
                mServiceInfo.setMoneyType(UnitUtils.getSettingMoneyType().toUpperCase());
            }
        }
    }

    private void initTitle() {
        mPayIncludeLayout.setTitle(getString(R.string.price_attribute_inclusion));
        mPayExcludeLayout.setTitle(getString(R.string.price_attribute_exclusion));
    }

    private void bindValueToLayout(int... types) {
        for (int type : types) {
            setValueInContent(type);
        }
    }

    private void updatePriceType() {
        if (priceType.equals(ServiceInfo.PAYWAY_FREE)) {
            payCountLayout.setVisibility(View.GONE);
            mPayCountContent.setText("");
            mMoneyEndView.setVisibility(View.GONE);
            currencyLayout.setVisibility(View.GONE);
        } else if (priceType.equals(ServiceInfo.PAYWAY_PER)) {
            payCountLayout.setVisibility(View.VISIBLE);
            mMoneyEndView.setVisibility(View.VISIBLE);
            currencyLayout.setVisibility(View.VISIBLE);
        } else if (priceType.equals(ServiceInfo.PAYWAY_ALL)) {
            payCountLayout.setVisibility(View.VISIBLE);
            mMoneyEndView.setVisibility(View.GONE);
            currencyLayout.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(R.id.pay_way_layout)
    public void selectPayWay() {
        ChoiceDialog dialog = ChoiceDialog.getInstance();
        dialog.setDialogTitleVisibility(false);
        List<MultiItem> multiItemList = new ArrayList<MultiItem>();
        String[] hostArray = getResources().getStringArray(R.array.pay_ways_array);
        for (String apiString : hostArray) {
            MultiItem multiItem = new MultiItem(apiString);
            multiItemList.add(multiItem);
        }
        dialog.setDialogMessageVisibility(false);
        dialog.setDialogMultiStyleSetting(multiItemList, new ChoiceDialog.DialogStyleMultiCallback() {
            @Override
            public boolean onMultiItemClick(MultiItem multiItem, int position) {
                if (!TextUtils.isEmpty(multiItem.getItemTitle())) {
                    priceType = position + "";
                    updatePriceType();
                    bindPayType(multiItem.getItemTitle());
                }
                return false;
            }
        });
        showDialogFragment(dialog);
    }


    private void initNavigation() {
        mPayIncludeLayout.setNavigateAction(new EditDetailLayout.NavigateAction() {
            @Override
            public void navigate() {
                if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()) {
                    TrackUtil.trackScreenName("/insider/trips/create/set/price/include");
                } else {
                    TrackUtil.trackScreenName("/insider/trips/edit/set/price/include");
                }
                Bundle bundle = new Bundle();
                bundle.putString(ParaEditActivity.TITLE_KEY, getString(R.string.price_attribute_inclusion));
                bundle.putInt(ParaEditActivity.MAX_LIMIT_KEY, 1500);
                if (!ArrayUtil.isNullOrEmpty(includePayList)) {
                    bundle.putCharSequenceArrayList(ParaEditActivity.PARA_KEY, includePayList);
                }
                Intent intent = new Intent(getContext(), ParaEditActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, PAY_INCLUDE_TYPE);
            }
        });

        mPayExcludeLayout.setNavigateAction(new EditDetailLayout.NavigateAction() {
            @Override
            public void navigate() {
                if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()) {
                    TrackUtil.trackScreenName("/insider/trips/create/set/price/not_include");
                } else {
                    TrackUtil.trackScreenName("/insider/trips/edit/set/price/not_include");
                }
                Bundle bundle = new Bundle();
                bundle.putString(ParaEditActivity.TITLE_KEY, getString(R.string.price_attribute_exclusion));
                bundle.putInt(ParaEditActivity.MAX_LIMIT_KEY, 1500);
                if (!ArrayUtil.isNullOrEmpty(excludePayList)) {
                    bundle.putCharSequenceArrayList(ParaEditActivity.PARA_KEY, excludePayList);
                }
                Intent intent = new Intent(getContext(), ParaEditActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, PAY_EXCLUDE_TYPE);
            }
        });

    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            ArrayList<CharSequence> highList = data.getCharSequenceArrayListExtra(ParaEditActivity.PARA_KEY);
            if (requestCode == PAY_INCLUDE_TYPE) {
                includePayList.clear();
                if (!ArrayUtil.isNullOrEmpty(highList)) {
                    includePayList.addAll(highList);
                }
            } else if (requestCode == PAY_EXCLUDE_TYPE) {
                excludePayList.clear();
                if (!ArrayUtil.isNullOrEmpty(highList)) {
                    excludePayList.addAll(highList);
                }

            }
            setValueInContent(requestCode);
        }
    }


    @OnClick(R.id.currency_layout)
    protected void selectCurrencyLayout() {
        OrderBusiness.getRates(mApiProxy, 0, 20);
    }

    private void bindPayType(String text) {
        if (text == null) {
            mPayWayContent.setText("");
        } else {
            mPayWayContent.setText(text);
        }
    }

    private void bindPrice(String text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        String formatText = NumberUtils.getMoneyFormat(text);
        mPayCountContent.setText(formatText);
        mPayCountContent.setSelection(formatText.length());
    }

    private void setValueInContent(int contentType) {
        switch (contentType) {
            case PAY_TYPE:
                if (!TextUtils.isEmpty(priceType)) {
                    int priceIndex = Integer.parseInt(priceType);
                    bindPayType(getResources().getStringArray(R.array.pay_ways_array)[priceIndex]);
                } else {
                    bindPayType(null);
                }
                break;
            case PRICE_TYPE:
                    bindPrice(price);
                break;
            case PAY_INCLUDE_TYPE:
                setValueToLayout(mPayIncludeLayout, includePayList);
                break;
            case PAY_EXCLUDE_TYPE:
                setValueToLayout(mPayExcludeLayout, excludePayList);
                break;
            case PAY_CURRENCY_TYPE:
                currencyLayout.setmRightText(mServiceInfo.getMoneyType());
                mMoneyTypeView.setText(mServiceInfo.getMoneyType());
                break;

        }
    }

    private void setValueToLayout(EditDetailLayout editDetailLayout, List<CharSequence> paraTextList) {
        List<Para> paraList = new ArrayList<>();
        if (!ArrayUtil.isNullOrEmpty(paraTextList)) {
            for (CharSequence charSequence : paraTextList) {
                Para para = new Para(charSequence);
                paraList.add(para);
            }
        }
        editDetailLayout.setParaList(paraList);
    }

    @Override
    public boolean onBackPressed() {
        saveAction();
        InputMethodManager ma = (InputMethodManager) getHostActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (getHostActivity().getCurrentFocus()!=null){
            ma.hideSoftInputFromWindow(getHostActivity().getCurrentFocus().getApplicationWindowToken(),0);
        }
        return super.onBackPressed();
    }


    private int getPrice() {
        return (int)NumberUtils.parseFloat(mPayCountContent.getText().toString());
    }

    /**
     * 选择返回键依然要保存数据
     *
     * @param fromKey
     * @return
     */
    @Override
    public boolean onBackPressed(boolean fromKey) {
        if (fromKey) {
            saveAction();
        }
        return super.onBackPressed(fromKey);
    }

    private void saveAction() {
        mServiceInfo.setPriceType(priceType);
        mServiceInfo.setPrice(getPrice() + "");
        mServiceInfo.setMoneyType(currencyLayout.getmRightText().toString());
        if (!ArrayUtil.isNullOrEmpty(includePayList)) {
            mServiceInfo.setFeeInclude(ParaProxy.getInstance().outputPara(includePayList));
        }
        if (!ArrayUtil.isNullOrEmpty(excludePayList)) {
            mServiceInfo.setFeeExclude(ParaProxy.getInstance().outputPara(excludePayList));
        }
        if (mTripMainUpdater != null) {
            mTripMainUpdater.renderPayInstruction();
        }
    }

    public void onDestroy() {
        super.onDestroy();
        mTripMainUpdater = null;
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.price);
        config.mTopbarRightAreaName = getString(R.string.query_icon);
        config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;

        return config;
    }

    @Override
    public void onTopbarLeftPress() {


        onBackPressed();
    }

    @Override
    public void onTopbarRightPress() {
        startOtherPage();
    }

    private void startOtherPage(){
        if (notice != null) {
            Intent intent = new Intent(getHostActivity(), ExplainActivity.class);
            intent.putExtra(ExplainActivity.KEY_CODE, ExplainActivity.SHOW_INFO_ABOUT_FEE_DESCRIPTION);
            intent.putParcelableArrayListExtra("notice", notice);
            ExplainActivity.startActivityBy(getHostActivity(), intent);
        }
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response.isResponseNormal() ) {
            if (ApiManager.GET_RATES.equals(response.getApiName())&& response.result instanceof List) {
                List<Rate> rateList = (List<Rate>) response.result;
                boolean hasUSD = false;
                for (int i = 0; i < rateList.size(); i++) {
                    Rate rate = rateList.get(i);
                    if ("USD".equalsIgnoreCase(rate.currency)) {
                        hasUSD = true;
                    }
                }
                if (!hasUSD) {
                    Rate usd = new Rate("", "", "USD");
                    rateList.add(0, usd);
                }
                PriceProxy.getInstance().showCurrencySelect(getHostActivity(), rateList, new PriceProxy.CurrencyCallback() {
                    @Override
                    public void onCurrencySelect(String currency) {
                        currencyLayout.setmRightText(currency);
                        mServiceInfo.setMoneyType(currency);
                        mMoneyTypeView.setText(currency);

                    }
                });
            } else if (ApiManager.GET_INFOPAGES.equals(response.getApiName()) &&response.result instanceof PayMode) {
                PayMode payMode = (PayMode) response.result;
                notice = payMode.getNotice();

            } else {
                if (TextUtils.isEmpty(response.msg)) {
                    ToastUtil.toast(response.msg);
                }
            }
        }
        return false;
    }


}
